package com.global.college.utils;


import com.global.college.api.IDownloadListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author Zhangzs
 * @create 2019/9/18 0018
 */
public class OkhttpUpdate {
    private final String TAG = this.getClass().getSimpleName();
    //请求JSON格式类型
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public OkHttpClient okHttpClient;

    private OkhttpUpdate() {
        okHttpClient = new OkHttpClient();
    }

    private static OkhttpUpdate okHttpUtils = new OkhttpUpdate();

    public static OkhttpUpdate getInstance() {
        return okHttpUtils;
    }


    public WeakHandler h = new WeakHandler();


    public interface RequestCallBack {
        void onResponse(String result);

        void onFailure(Call call, IOException response);
    }

    public void postJson(String url, String json, final RequestCallBack requestCallBack, String token) {
        RequestBody requestBody = RequestBody.create(JSON, json);
        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("head-token", token)
                .addHeader("token-type", "")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        //发送请求获取响应
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Call call, final IOException e) {
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        requestCallBack.onFailure(call, e);
                    }
                });
            }


            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                final String result = response.body().string();
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            requestCallBack.onResponse(result);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


    }

    /**
     * @param url      下载连接
     * @param saveDir  储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void download(final String url, final String saveDir, final IDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                // 下载失败
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onDownloadFailed();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = FileUtils.isExistDir(saveDir);
                ///storage/emulated/0/download
                try {
                    is = response.body().byteStream();
                    final long total = response.body().contentLength();
                    File file = new File(savePath, FileUtils.getNameFromUrl(url));
                    // http://192.168.31.99:8080/aa1.apk
                    // http://heshu.shop/app/home/view/default/public/wallet_1.2.1.apk
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        final int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        final long finalSum = sum;
                        h.post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onDownloading(progress);
                            }
                        });
                    }
                    fos.flush();
                    // 下载完成
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onDownloadSuccess();
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    h.post(new Runnable() {
                        @Override
                        public void run() {

                            listener.onDownloadFailed();
                        }
                    });

                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }
}
